using System;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;


namespace Com.Phyfun.Business
{
    public class Translate
    {/// <summary>
        /// Translates the text.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="languagePair">The language pair.</param>
        /// <returns></returns>
        public static string TranslateText(string input, string languagePair)
        {
            Encoding encoding = Encoding.UTF7;
            if (!string.IsNullOrEmpty(languagePair))
            {
                if (languagePair.EndsWith("ar"))
                {
                    encoding = Encoding.GetEncoding("ISO-8859-6");
                }
                else if (languagePair.EndsWith("ja"))
                {
                    encoding = Encoding.GetEncoding("ISO-2022-JP");
                } if (languagePair.EndsWith("ko"))
                {
                    encoding = Encoding.GetEncoding("ISO-2022-KR");
                }
            }
            return TranslateText(input, languagePair, encoding);
        }

        /// <summary>
        /// Translate Text using Google Translate
        /// </summary>
        /// <param name="input">The string you want translated</param>
        /// <param name="languagePair">2 letter Language Pair, delimited by "|". 
        /// e.g. "en|da" language pair means to translate from English to Danish</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>Translated to String</returns>
        public static string TranslateText(string input, string languagePair, Encoding encoding)
        {
            string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);

            string result = String.Empty;

            using (WebClient webClient = new WebClient())
            {
                webClient.Encoding = encoding;
                result = webClient.DownloadString(url);
                result = result.Substring(result.IndexOf("id=result_box"));
                result = result.Substring(result.IndexOf(">") + 1);
                result = result.Substring(result.IndexOf(">") + 1);
                result = result.Substring(0, result.IndexOf("<"));
            }

            return result;
        }

    }
}
